package com.example.zg.androidnewview;

import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;

public class CollapsingToolbarLayoutActivity extends AppCompatActivity {
    private static final String TAG = "CollapsingToolbarLayout";
    private AppBarLayout appBarLayout;
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private Toolbar toolbar;

    private float y=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collapsing_toolbar_layout);

        appBarLayout=findViewById(R.id.appBarLayout);
        collapsingToolbarLayout=findViewById(R.id.collapsingToolbarLayout);
        toolbar=findViewById(R.id.toolbar2);

        setSupportActionBar(toolbar);
        //使用CollapsingToolbarLayout必须把title设置到CollapsingToolbarLayout上，
        //设置到Toolbar上则不会显示
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if(y==0){
                    y=-(appBarLayout.getY()+appBarLayout.getHeight()-(toolbar.getY()+toolbar.getHeight()));
                    Log.i(TAG, "onOffsetChanged: y="+y);
                }
                Log.i(TAG, "onOffsetChanged: verticalOffset="+verticalOffset);
                if(verticalOffset<=y){
                    collapsingToolbarLayout.setTitle("标题");
                    Log.i(TAG, "onOffsetChanged: 显示标题");
                }else{
                    collapsingToolbarLayout.setTitle("");
                    Log.i(TAG, "onOffsetChanged: 隐藏标题");
                }
            }
        });



    }



}
